import Vue from 'vue'
import store from '@/store'
import request from '@/utils/request/index.js'
import { getTotalUnreadCount } from "./user.js";

import * as RongIMLib from '@rongcloud/imlib-v4'
const im = RongIMLib.init({ appkey: 'uwd1c0sxukb51'});
Vue.prototype.$im = im // 挂载到vue
Vue.prototype.$RongIMLib = RongIMLib // 挂载到vue

// 事件监听
im.watch({
  // 监听会话列表变更事件
  conversation (event) {
    // 1.获取初始会话列表
    const conversationList = store.state.conversationList
    // 2.获取发生变更的会话列表
    const updatedConversationList = event.updatedConversationList;
    // 3.通过 im.Conversation.merge 计算最新的会话列表
    const latestConversationList = im.Conversation.merge({ conversationList, updatedConversationList })
    // 4.改变vuex里的会话列表
    store.commit('SET_CONVERSATIONLIST',latestConversationList)
    getTotalUnreadCount() // 更新未读数
  },
  // 监听消息通知
  message (event) {
    const message = event.message;
    // 别人发过来的消息
    if(message.messageDirection === 2){
      if(message.senderUserId === store.state.receiverUser.imId){ // 并且为 当前会话用户，直接push进去
        const newMsgList = [...store.state.msgList,message]
        store.commit('SET_MESSAGE_LIST',newMsgList)
      }else{
        getTotalUnreadCount() // 更新未读数
      }
      console.log(message,'接收新消息')
    }
  },
  // 监听 IM 连接状态变化 0：链接成功
  status (event) {
    if(event.status === 0){ // 连接成功-获取初始会话列表-存入vuex
      im.Conversation.getList().then(conversationList => {
        store.commit('SET_CONVERSATIONLIST',conversationList)
        getTotalUnreadCount() // 更新未读数
      });
    }
    console.log('IM连接状态', event.status,event.status === 0 ? '成功' : (event.status === 1 ? '连接中...' : '连接失败'));
    if(event.status === 6){
      request({url: '/store/mini/account/getInfo',method: 'POST'})
    }
  },
})